﻿using System.Collections.Generic;
using ML.Entity;
using ML.IBusiness;
using ML.IRepository;
using System.Linq;
using ML.Utils;

namespace ML.Business
{
    /// <summary>
    /// 商户结算业务实现类
    /// </summary>
    public class SettlementBusiness : ISettlementBusiness
    {
        private readonly ISettlementRepository settlementRepository;
        public SettlementBusiness(ISettlementRepository _settlementRepository)
        {
            settlementRepository = _settlementRepository;
        }

        public BaseResult<Pager<SettlementResponse>> List(SettlementSearch settlementSearch)
        {
            //根据传递的条件查询
            Pager<SettlementResponse> data = settlementRepository.List(settlementSearch);
            foreach (var row in data.rows)
            {
                row.StatusName = PublicEnumHelper.GetEnumDesc(typeof(SettlementStatu), row.SettlementStatus);
            }
            return new BaseResult<Pager<SettlementResponse>>(200, data);
        }

        public BaseResult<bool> Add(SettlementEntity settlementEntity)
        {
            //首先判断商户内部是否含有未处理的单子，如果含有未处理的则不允许在添加
            var data = settlementRepository.GetSettlementByMerchantId(settlementEntity.MerchantId);
            if (data.Count() > 0)
            {
                var settlementStatus = data.Where(c => c.SettlementStatus == (int)SettlementStatu.submitted);
                if (settlementStatus.Count() > 0)
                {
                    return new BaseResult<bool>(2001, false);
                }
            }

            settlementEntity.Number = CommonUtil.ReadDateTime() + CommonUtil.LiterReadRandom(4);
            var isTrue = settlementRepository.Add(settlementEntity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<bool> UpdateSettlementStatus(string Id, int Type, string Optioner, string Remark)
        {
            //2-已完成；3-失败；4-取消
            var isTrue = false;
            if (Type == (int)SettlementStatu.success)
            {
                //已完成则修改结算单状态为已完成并且修改资金账户中的已提现金额申请结算的金额
                var data = settlementRepository.GetById(Id);
                isTrue = settlementRepository.UpdateSettlementStatuSucccess(Id, data, Optioner);
            }
            if (Type == (int)SettlementStatu.fail)
            {
                isTrue = settlementRepository.UpdateSettlementStatu(Id, (int)SettlementStatu.fail, Remark, Optioner);
            }
            if (Type == (int)SettlementStatu.cancel)
            {
                isTrue = settlementRepository.UpdateSettlementStatu(Id, (int)SettlementStatu.cancel, Remark, Optioner);
            }
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }
    }
}